package com.witmore.skyline.web.controller;

import com.jk.common.annotation.NoLoginRequired;
import com.witmore.skyline.web.controller.vo.param.DeviceOilListParamVO;
import com.witmore.skyline.web.controller.vo.result.ResponseResult;
import com.witmore.skyline.web.service.DeviceOilService;
import com.witmore.skyline.web.service.OilAnalyzer;
import com.witmore.skyline.web.service.third.yjx.dto.DeviceOilDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/api/develop")
public class OilController {

    @Autowired
    private DeviceOilService deviceOilService;
    /**
     * POST /api/oil/analyze
     * 请求体是一个数组：
     * [
     *   { "oilLevel": 10, "time": "2025-11-14 10:00:00" },
     *   { "oilLevel": 15, "time": "2025-11-14 10:01:00" },
     *   ...
     * ]
     */
    @NoLoginRequired
    @GetMapping("/analyze")
    public ResponseResult<OilAnalyzer.OilDetail> analyze(@RequestParam("start") String start,
                                                         @RequestParam("end") String  end,
                                                         @RequestParam("deviceSn") String deviceSn) {
        // start 转换 LocalDateTime格式
        LocalDateTime startTime = stringConvertDateTime(start);
        // end 转换 LocalDateTime格式
        LocalDateTime endTime = stringConvertDateTime(end);
        DeviceOilListParamVO deviceOilListParamVO = DeviceOilListParamVO.builder()
                .deviceSn(deviceSn)
                // 2025-11-08 11:23:33  2025-11-14 11:23:33
                .startTime(startTime)
                .endTime(endTime)
                .build();
        ResponseResult<List<DeviceOilDTO>> listResponseResult = deviceOilService.oilListV2(deviceOilListParamVO);
        List<DeviceOilDTO> samples = listResponseResult.getData();
        // 按照 时间 升序
        samples.sort(Comparator.comparing(DeviceOilDTO::getTime));
        return ResponseResult.success(OilAnalyzer.getOilPercent(samples));
    }

    public static LocalDateTime stringConvertDateTime(String dateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(dateTime, formatter);
    }
}
